package com.chenyue.cm.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.user.dao.JdAppUserRoleMapper;
import com.chenyue.cm.user.domain.JdAppUserRole;
import com.chenyue.cm.user.service.JdAppUserRoleService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;


/**
 * @author chenyue-cm
 */
@Service(value = "JdAppUserRoleService")
public class JdAppUserRoleServiceImpl extends BaseServiceImpl<JdAppUserRole> implements JdAppUserRoleService {

    private final JdAppUserRoleMapper jdAppUserRoleMapper;

    public JdAppUserRoleServiceImpl(@Qualifier("jdAppUserRoleMapper") JdAppUserRoleMapper jdAppUserRoleMapper) {
        this.jdAppUserRoleMapper = jdAppUserRoleMapper;
    }

    @Override
    @Resource(name = "jdAppUserRoleMapper")
    public void setBaseMapper(LcBaseMapper<JdAppUserRole, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public void setRole(Integer userId, Integer role) {
        final JdAppUserRole one = jdAppUserRoleMapper.selectOne(
                new LambdaQueryWrapper<JdAppUserRole>()
                        .eq(JdAppUserRole::getUserId, userId)
                        .eq(JdAppUserRole::getRoleId, role)
        );
        if (one == null) {
            JdAppUserRole userRole = new JdAppUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(role);
            final int success = jdAppUserRoleMapper.insert(userRole);
            if (success == 0) {
                throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
            }
        }
    }
}
